package menuService

import (
	"encoding/json"
	"fmt"
	"gitee.com/yangguoliang001/go-gin-vue3/BO"
	"gitee.com/yangguoliang001/go-gin-vue3/QO"
	"gitee.com/yangguoliang001/go-gin-vue3/config"
	"gitee.com/yangguoliang001/go-gin-vue3/model"
	"gitee.com/yangguoliang001/go-gin-vue3/pkg/response"
	"gitee.com/yangguoliang001/go-gin-vue3/util/code"
	"gitee.com/yangguoliang001/go-gin-vue3/vo"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"github.com/spf13/cast"
)

func (m *menuService) QueryMenuActionList(c *gin.Context, id string) (res vo.MenuActionVO, err error) {
	var methodList []string
	apiList, err := m.menuActionDao.QueryMenuActionListByMenuId(cast.ToInt32(id))
	method, err := m.menuActionDao.QueryMethodList()
	if err != nil {
		response.Fail(c, code.MenuListActionError, code.Text(code.MenuListActionError), gin.H{"realErr": err})
		return vo.MenuActionVO{}, err
	}
	for _, v := range method {
		methodList = append(methodList, v.Method)
	}
	fmt.Println("apiList", methodList)

	return vo.MenuActionVO{
		MenuActionList: apiList,
		MethodList:     methodList,
	}, nil
}

func (m *menuService) AddMenuAction(c *gin.Context, apiReq QO.AddMenuActionReq) (err error) {

	token, exist := c.Get("token")
	if !exist {
		response.Fail(c, code.AdminLoginError, code.Text(code.AdminLoginError), gin.H{"realErr": "用户未登录"})
		return errors.New("context 获取 token 失败")
	}
	userInfo := m.cache.Get(config.RedisKeyPrefixLoginUser + fmt.Sprintf("%s", token))
	var sessionUser BO.SessionUserInfo
	_ = json.Unmarshal([]byte(userInfo.Val()), &sessionUser)

	m.logger.Info("AddAuthorizedApi cache userInfo: " + userInfo.Val())

	var authApi model.MenuActionDo
	authApi.MenuId = cast.ToInt32(apiReq.MenuId)
	authApi.Method = apiReq.Method
	authApi.Api = apiReq.Api
	authApi.CreatedUser = sessionUser.Username
	authApi.IsDeleted = -1
	rowAffects, err := m.menuActionDao.AddMenuAction(authApi)

	if err != nil {
		response.Fail(c, code.MenuCreateError, code.Text(code.MenuCreateError), gin.H{"realErr": err})
		return err
	}

	if rowAffects == 0 {
		response.Fail(c, code.MenuCreateError, "数据已存在", gin.H{})
		return errors.New("数据已存在")
	}
	return nil
}

func (m *menuService) DeleteMenuAction(c *gin.Context, id string) (err error) {
	err = m.menuActionDao.DeleteMenuAction(id)
	if err != nil {
		response.Fail(c, code.AuthorizedDeleteAPIError, code.Text(code.AuthorizedDeleteAPIError), gin.H{"realErr": err})
		return err
	}
	return nil
}
